package org.simplesocket.simplenettycore.handlers;

import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import lombok.extern.slf4j.Slf4j;
import org.simplesocket.simplenettycore.protocol.SimpleProtocol;
import org.simplesocket.simplenettycore.session.ChannelAttr;
import org.simplesocket.simplenettycore.session.ClientSessionContext;
import org.simplesocket.simplenettycore.utils.CommonUtils;
import org.simplesocket.simplenettycore.utils.SimpleNettyUtils;

import java.util.Map;

@Slf4j
@ChannelHandler.Sharable
public class EncryptHandler extends ChannelOutboundHandlerAdapter {
    
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
        SimpleProtocol sp = (SimpleProtocol) msg;
        try {
            ClientSessionContext csc = ctx.channel().attr(ChannelAttr.CLIENT_SESSION_CONTEXT).get();
            String aes = csc.getBothAes();
            String data = sp.getData();
            
            String encryptedData = SimpleNettyUtils.AESUtil.encrypt(data, aes);
            sp.setData(encryptedData);
            
            ctx.write(sp,promise);
        }catch (Exception e){
            log.error("Encrypt client '{}' data error,sessionID is '{}',\n",
                    ctx.channel().remoteAddress(),sp.getSessionID());
            CommonUtils.printException(e);
            
            ctx.write(SimpleProtocol.builder()
                            .type(sp.getType())
                            .status(SimpleProtocol.Status.ERROR)
                            .sessionID(sp.getSessionID())
                            .uri(sp.getUri())
                            .data(JSON.toJSONString(Map.of("sessionID","Protocol translate error")))
                    .build(),promise);
        }
    }
}
